<!--<template>-->
<!--  <div class="app-container">-->
<!--    <Month />-->
<!--    &lt;!&ndash; 日历和日报表格切换按钮 &ndash;&gt;-->
<!--    <el-switch v-model="isShowDailyTable" active-text="显示日报日历" inactive-text="显示本月日报表格">-->
<!--    </el-switch>-->

<!--    &lt;!&ndash; <el-button>{{显示日报日历}}</el-button> &ndash;&gt;-->
<!--    <el-calendar v-model="value" v-show="isShowDailyTable">-->
<!--      <template slot="dateCell" slot-scope="{date, data}">-->
<!--        <div style="height: 75%;" :class="data.isSelected ? 'is-selected' : ''" @click="getDaliyContent(data);">-->
<!--          {{ data.day.split('-').slice(1).join('-').split('-').slice(1).join('-') }}-->
<!--          {{ isSelected(data.day) ? '✔️' : '' }}-->
<!--        </div>-->
<!--        &lt;!&ndash; <span>1111</span> &ndash;&gt;-->
<!--        <div v-if="isShowAddButton(data.day) && parseInt(dateFormat(data.day))==new Date().getDate() "></div>-->
<!--      </template>-->
<!--    </el-calendar>-->
<!--    &lt;!&ndash; 添加今日工作日报按钮 &ndash;&gt;-->
<!--    <AddDailyForm :refresh="refresh" :AddDailyForm="AddDailyForm" />-->
<!--    &lt;!&ndash; 本月日报和日历卡片切换按钮 &ndash;&gt;-->
<!--    <dailytable v-show="!isShowDailyTable" :dailyDataTable="dailyDataTable" />-->
<!--  </div>-->
<!--</template>-->

<!--<script>-->
<!--import "@riophae/vue-treeselect/dist/vue-treeselect.css";-->
<!--import { dailyContent } from "@/api/request";-->
<!--import { monthContent, getMonthly } from "@/api/request";-->
<!--import Month from "@/components/monthly";-->
<!--import AddDailyForm from "@/components/Daily/index.vue";-->
<!--import dailytable from "@/components/DailyTable/index"-->
<!--export default {-->
<!--  name: "Daily",-->
<!--  data() {-->
<!--    return {-->
<!--      // 点击切换日报表格和日历按钮-->
<!--      isShowDailyTable: true,-->
<!--      userId: this.$store.state.user.id,-->
<!--      day: 19,-->
<!--      clickMonth: '',-->
<!--      value: new Date(),-->
<!--      dialogVisible: false,-->
<!--      today: "", //当前日期-->
<!--      daliyContent: "", //接收到的工作日报内容-->
<!--      dailyDataTable: [],//进入页面请求本月日报信息-->
<!--      //查询日报参数-->
<!--      queryParams: {-->
<!--        //用户名-->
<!--        username: this.$store.state.user.name,-->
<!--        //年-->
<!--        year: "",-->
<!--        //月-->
<!--        month: "",-->
<!--        //日-->
<!--        day: ""-->
<!--      },-->

<!--      queryDayList: {-->
<!--        //调用获取本月日报接口参数-->
<!--        year: new Date().getFullYear(),-->
<!--        month: new Date().getMonth() + 1,-->
<!--        type: "1 "-->
<!--      },-->
<!--      tempDayList: [], //存放日报数据-->
<!--      dayArr: [], //存放本月填写日报日期-->
<!--      isShowAdd: false, //是否展示本日添加按钮-->
<!--      AddDailyForm: {-->
<!--        title: "日报", //日报标题-->
<!--        type: "1", //确认是日报-->
<!--        id: "", //需要传入id-->
<!--        dailyContent: "", //传入日报内容-->
<!--        isLeave: false,-->
<!--        btnName: "按钮",-->
<!--        time: "",-->
<!--        isShow: false,-->
<!--        // isDisable:false-->
<!--      }-->
<!--    };-->
<!--  },-->
<!--  components: {-->
<!--    Month,-->
<!--    AddDailyForm,-->
<!--    dailytable-->
<!--  },-->
<!--  mounted() {-->
<!--    //  渲染页面时请求本月填写日报的日期-->
<!--    this.getMonthList(this.queryDayList);-->
<!--    this.test()-->
<!--  },-->
<!--  methods: {-->
<!--    test() {-->
<!--      let button = document.getElementsByClassName("el-button&#45;&#45;plain")[0]-->
<!--      button.addEventListener('click', () => {-->
<!--        this.queryDayList.month -= 1-->
<!--        if (this.queryDayList.month === 0) {-->
<!--          this.queryDayList.month = 12-->
<!--          this.queryDayList.year -= 1-->
<!--        }-->
<!--        this.getMonthList(this.queryDayList)-->
<!--      })-->

<!--      let button2 = document.getElementsByClassName("el-button&#45;&#45;plain")[1]-->
<!--      button2.addEventListener('click', () => {-->
<!--        this.queryDayList.month = new Date().getMonth() + 1-->
<!--        this.getMonthList(this.queryDayList)-->
<!--      })-->

<!--      let button3 = document.getElementsByClassName("el-button&#45;&#45;plain")[2]-->
<!--      button3.addEventListener('click', () => {-->
<!--        this.queryDayList.month += 1-->
<!--        if (this.queryDayList.month === 13) {-->
<!--          this.queryDayList.month = 1-->
<!--          this.queryDayList.year += 1-->
<!--        }-->
<!--        this.getMonthList(this.queryDayList)-->
<!--      })-->
<!--    },-->
<!--    //获取本月月报信息-->
<!--    // getDailyByMonth(){-->
<!--    //   getMonthly({month:this.clickMonth,userId:this.userId}).then(res=>{-->
<!--    //     this.AddDailyForm.isDisable = true-->
<!--    //   }).catch((err)=>{-->
<!--    //     console.log(err)-->
<!--    //   })-->
<!--    // },-->
<!--    //请求本月填写日报的日期-->
<!--    getMonthList(params) {-->
<!--      monthContent(params).then(res => {-->
<!--        this.tempDayList = res.data;-->
<!--        this.tempDayList.forEach(item => {-->
<!--          let date = item.year + "-" + item.month + "-" + item.day;-->
<!--          this.dayArr.push(date);-->
<!--        });-->
<!--        this.dailyDataTable = res.data-->
<!--      });-->
<!--    },-->
<!--    refresh() {-->
<!--      this.getMonthList(this.queryDayList);-->
<!--      this.isSelected();-->
<!--    },-->
<!--    // 传入年月日转成日-->
<!--    dateFormat(data) {-->
<!--      return data-->
<!--        .split("-")-->
<!--        .slice(1)-->
<!--        .join("-")-->
<!--        .split("-")-->
<!--        .slice(1)-->
<!--        .join("-");-->
<!--    },-->
<!--    //日历当日是否显示添加日报按钮-->
<!--    isShowAddButton(day) {-->
<!--      return this.dayArr.indexOf(parseInt(this.dateFormat(day))) === -1;-->
<!--    },-->
<!--    //判断是否勾选-->
<!--    isSelected(date) {-->
<!--      var isSelect = false;-->
<!--      let month = parseInt(date.split("-")[1]);-->
<!--      let day = parseInt(date.split("-")[2]);-->
<!--      let year = parseInt(date.split("-")[0]);-->
<!--      date = year + "-" + month + "-" + day;-->
<!--      for (var i = 0; i < this.dayArr.length; i++) {-->
<!--        if (date == this.dayArr[i]) {-->
<!--          isSelect = true;-->
<!--        }-->
<!--      }-->
<!--      return isSelect;-->
<!--    },-->
<!--    /*-->
<!--        默认显示当天内容-->
<!--      */-->
<!--    isShow(data) {-->
<!--      var today = new Date();-->
<!--      var dd = String(today.getDate()).padStart(2, "0");-->
<!--      var mm = String(today.getMonth() + 1).padStart(2, "0");-->
<!--      var yyyy = today.getFullYear();-->
<!--      today = yyyy + "-" + mm + "-" + dd;-->
<!--      this.today = today;-->
<!--      if (this.today == data) {-->
<!--        return true;-->
<!--      } else {-->
<!--        return false;-->
<!--      }-->
<!--    },-->
<!--    /*-->
<!--      处理日期方法-->
<!--      将点击日历获取的日期和现在日期进行比较-->
<!--      在今天和今天的日期之前的日期返回true-->
<!--      在未来的日期返回false-->
<!--    */-->
<!--    handlerTime(data) {-->
<!--      //鼠标获取的日期-->
<!--      this.queryParams.year = data.day.split("-")[0];-->
<!--      this.queryParams.month = parseInt(data.day.split("-")[1]);-->
<!--      this.queryParams.day = parseInt(data.day.split("-")[2]);-->
<!--      var choseDay =-->
<!--        this.queryParams.year +-->
<!--        "-" +-->
<!--        this.queryParams.month +-->
<!--        "-" +-->
<!--        this.queryParams.day;-->
<!--      //  当前的日期-->
<!--      var today = new Date();-->
<!--      var dd = String(today.getDate()).padStart(2, "0");-->
<!--      var mm = String(today.getMonth() + 1).padStart(2, "0");-->
<!--      var yyyy = today.getFullYear();-->
<!--      today = yyyy + "-" + mm + "-" + dd;-->
<!--      // console.log('本日日期:',today)-->
<!--      //日期转数字判断-->
<!--      var time1 = new Date(choseDay);-->
<!--      var time2 = new Date(today);-->
<!--      return time2.getTime() >= time1.getTime();-->
<!--    },-->
<!--    /** 点击日历卡片查询日报信息 */-->
<!--    getDaliyContent(data) {-->
<!--      this.dialogVisible = true;-->
<!--      this.daliyContent = "";-->
<!--      this.clickMonth = parseInt(data.day.split('-')[1])-->
<!--      // 点击按钮获取当前卡片月份-->
<!--      console.log("获取到的clickMonth", this.clickMonth)-->
<!--      // this.getDailyByMonth();-->
<!--      //假如点击日历的日期是当前日期之前-->
<!--      if (this.handlerTime(data)) {-->
<!--        //调用接口-->
<!--        dailyContent(this.queryParams)-->
<!--          .then(response => {-->
<!--            this.centerDialogVisible = true;-->
<!--            this.AddDailyForm.id = response.data.id;-->
<!--            this.AddDailyForm.dailyContent = response.data.briefSummary;-->
<!--            this.AddDailyForm.time = data.day;-->
<!--            this.AddDailyForm.isShow = true;-->
<!--          })-->
<!--          .catch(() => {-->
<!--            this.AddDailyForm.isShow = true;-->
<!--            this.AddDailyForm.dailyContent = "";-->
<!--            this.AddDailyForm.time = data.day;-->
<!--          });-->
<!--      } else {-->
<!--        this.$message.warning("当前日期不可填写")-->
<!--      }-->
<!--    }-->
<!--  }-->
<!--};-->
<!--</script>-->
<!--<style scoped>-->

<!--</style>-->


<template>
  <div>
    <div style="display: flex;justify-content: center;">
      <h2>考勤管理</h2>
    </div>
    <div style="display: flex;justify-content: right">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="请选择时间">
          <el-date-picker v-model="dataStr" value-format="yyyy-MM-dd" type="month"
                          placeholder="选择月"></el-date-picker>
        </el-form-item>
      </el-form>

    </div>
    <el-table border :data="tableData" style="width: 100%" size="small">
      <el-table-column fixed align="center" type="index" label="序号" width="50"/>
      <!-- 姓名列 -->
      <el-table-column fixed prop="nickName" label="姓名" width="100" align="center"></el-table-column>
      <!-- 考勤状态列 -->
      <el-table-column v-for="(day, index) in allDays" :key="index" :label="day + ''" align="center" width="50">
        <template slot-scope="scope">
          <div style="height: 100%;width: 100%;cursor: pointer" @click="handleLeave(day, scope.row.nickName)">
            <template v-for="item in scope.row.childClockingList">
              <el-popconfirm
                v-if="$store.getters.name==='lhf'||$store.getters.name==='admin'||$store.getters.name==='ls'"
                placement="top"
                width="260"
                confirm-button-text='修改'
                cancel-button-text='删除'
                @confirm="handleConfirm(item.clockingId)"
                @cancel="handleCancel(item.clockingId)"
                icon-color="blue"
                title="您要删除或者修改这条请假记录吗？"
                v-model="visible">
                <span slot="reference" @click="clickSquare(item.clockingId)"
                      style="cursor: pointer;color: gold;font-size: 25px"
                      v-if="parseInt(item.day) === parseInt(day) && item.type === '1'">★</span>
                <span slot="reference" @click="clickSquare(item.clockingId)"
                      style="cursor: pointer;font-size: 20px;color: #00afff"
                      v-if="parseInt(item.day) === parseInt(day) && item.type === '2'">〇</span>
              </el-popconfirm>
              <template v-else>
                  <span slot="reference" @click="clickSquare(item.clockingId)"
                        style="cursor: pointer;color: gold;font-size: 25px"
                        v-if="parseInt(item.day) === parseInt(day) && item.type === '1'">★</span>
                <span slot="reference" @click="clickSquare(item.clockingId)"
                      style="cursor: pointer;font-size: 20px;color: #00afff"
                      v-if="parseInt(item.day) === parseInt(day) && item.type === '2'">〇</span>
              </template>
            </template>
            <span style="height: 50px;opacity: 0">1</span>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div style="display: flex;justify-content: left;margin-left: 20px;">
      <el-form :inline="true" class="demo-form-inline">
        <span style="color: gold;font-size: 20px">★  </span><span>事假</span> <br>
        <span style="color: #00afff ;font-size: 20px">〇  </span><span>病假</span>
      </el-form>
    </div>
    <el-form :inline="true" class="demo-form-inline">

    </el-form>

    <!--    dialog对话框-添加 -->
    <el-dialog title="添加请假记录" :visible.sync="dialogVisible" width="30%">
      <el-form :rules="rules" ref="ruleForm" label-width="80px" :model="leaveForm">
        <el-form-item label="请假时间">
          <el-input disabled
                    :value="parseInt(this.dataStr.slice(0, 4))+'年'+parseInt(this.dataStr.slice(5, 7))+'月'+this.day+'日'"></el-input>
        </el-form-item>
        <el-form-item label="请假理由" prop="region">
          <el-select v-model="leaveForm.region" placeholder="请假理由">
            <el-option label="事假" :value="1"></el-option>
            <el-option label="病假" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="currentLeave('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>

    <!--dialog   修改-->
    <el-dialog title="修改请假记录" :visible.sync="updateDialog" width="30%">
      <el-form :rules="rules" ref="updateRuleForm" label-width="80px" :model="updateForm">
        <el-form-item label="请假时间">
          <el-input disabled
                    :value=updateForm.time></el-input>
        </el-form-item>
        <el-form-item label="请假理由" prop="region">
          <el-select v-model="updateForm.type" placeholder="请假理由">
            <el-option label="事假" :value="1"></el-option>
            <el-option label="病假" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateDialog = false">取 消</el-button>
        <el-button type="primary" @click="currentUpdate()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {deleteAttendance, getAttendanceById, getAttendanceList, leave, updateAttendance} from "@/api/attendance";

export default {
  data() {
    return {
      // currentDate: new Date(),
      tableData: [],
      allDays: [], // 保存所有的日期
      clickId: '',
      dataStr: new Date().getFullYear() + '-' + parseInt(new Date().getMonth() + 1) + "-" + '01',
      dialogVisible: false,
      visible: false,
      userName: '',
      day: '',
      updateDialog: false,
      dataArr: [],
      leaveForm: {
        time: '',
        region: 0
      },
      updateForm: {
        time: '213',
        type: 0
      },
      rules: {
        time: [
          {required: true, message: '请选择请假时间', trigger: 'blur'},
        ],
        region: [
          {required: true, message: '请选择请假理由', trigger: 'blur'}
        ],
      },
    };
  },
  watch: {
    'dataStr': {
      immediate: true,
      handler() {
        //const year = parseInt(this.dataStr.slice(0, 4))
        //const month = parseInt(this.dataStr.slice(5, 7))
        //this.getTableData(year, month)
        this.uinit()
      }
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    // 初始化
    uinit() {
      this.init();
      const year = parseInt(this.dataStr.slice(0, 4))
      const month = parseInt(this.dataStr.slice(5, 7))
      this.allDays = new Date(year, month, 0).getDate()
      this.getTableData(year, month)
    },
    // 发送修改事件
    currentUpdate() {
      updateAttendance({"id": this.clickId, "type": this.updateForm.type}).then(res => {
        if (res.code === 200) {
          this.$message.success("修改成功")
          this.updateDialog = false
          const year = parseInt(this.dataStr.slice(0, 4))
          const month = parseInt(this.dataStr.slice(5, 7))
          this.getTableData(year, month)
        }
      })
    },
    //弹出修改窗口
    handleConfirm(id) {
      this.clickId = id
      // 发起请求，获取updateForm的数据
      getAttendanceById(id).then(res => {
        this.updateForm.time = res.data.year + "-" + res.data.month + "-" + res.data.day
        this.updateForm.type = parseInt(res.data.type)
      })
      this.updateDialog = true
    },
    // 删除事件
    handleCancel(id) {
      deleteAttendance(id).then(res => {
        if (res.code === 200) {
          this.$message.success("删除成功")
          const year = parseInt(this.dataStr.slice(0, 4))
          const month = parseInt(this.dataStr.slice(5, 7))
          this.getTableData(year, month)
        }
      })
    },
    clickSquare(clockid) {
    },
    getTableData(year, month) {
      getAttendanceList({"year": year, "month": month}).then(res => {
        this.tableData = res.rows.filter(item => {
          return item.userId !== 1 && item.userId != 2
        })
        // this.tableData = res.rows
      })
    },
    //弹出对话框 如果当前年 月 日 有请假记录 则不弹出对话框
    handleLeave(day, username) {
      if (this.$store.getters.name === 'lhf' || this.$store.getters.name === 'admin' || this.$store.getters.name === 'ls') {

        const year = parseInt(this.dataStr.slice(0, 4))
        const month = parseInt(this.dataStr.slice(5, 7))
        this.userName = username
        this.day = parseInt(day)
        // 判断
        const userArr = this.tableData.filter(item => item.nickName === username)
        let flag = false
        userArr[0].childClockingList.forEach(item => {
          if (parseInt(item.day) === day) {
            flag = true
          }
        })
        if (!flag) {
          this.leaveForm = {}
          this.dialogVisible = true
        } else {
          // this.$message.warning(`${year}年${month}月${day}日 ${username} 已请假`)
          return false
        }
      }

    },
    // 点击弹出框中的确认触发
    currentLeave(formName) {
      const year = parseInt(this.dataStr.slice(0, 4))
      const month = parseInt(this.dataStr.slice(5, 7))
      //应该校验表单，formLeave为空发不出请求
      this.$refs[formName].validate((valid) => {
        if (valid) {
          leave({
            "nickName": this.userName,
            "type": parseInt(this.leaveForm.region),
            "year": year,
            "month": month,
            "day": parseInt(this.day)
          }).then(res => {
            if (res.code === 200) {
              this.$message.success("请假成功")
              this.dialogVisible = false
              this.getTableData(year, month)
            } else {
              this.$message.warning("error")
            }
          })

        } else {
          return false;
        }
      });
    },
    init() {
      // 获取所有日期
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = currentDate.getMonth() + 1;
      const daysInMonth = new Date(year, month, 0).getDate();
      const monthDays = new Date(year, month, 0).getDate()
      // 生成日期数组
      this.allDays = Array.from({length: daysInMonth}, (value, index) => index + 1);
    },
  },
};
</script>

<style lang="scss" scoped>
.el-table__row {
  td {
    cursor: pointer;
  }
}

.red {
  color: red;
}

.bold {
  font-weight: bold;
}

.blue {
  color: blue;
}

.size-20 {
  font-size: 20px;
}

.gray {
  color: gray;
}

// .skybluedark {
//   color: #009688;
// }
</style>
